package com.rybbaby.tss.front.tssAllocation.service.imp;

import com.google.common.collect.ImmutableMap;
import com.rybbaby.tss.core.utils.StringUtils;
import com.rybbaby.tss.core.web.service.imp.BaseServiceImp;
import com.rybbaby.tss.front.tssAllocation.dao.ITssAllocationDao;
import com.rybbaby.tss.front.tssAllocation.entity.TssAllocation;
import com.rybbaby.tss.front.tssAllocation.service.ITssAllocationService;
import com.rybbaby.tss.front.tssStudent.service.imp.TssStudentServiceImp;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.sql.Timestamp;
import java.util.List;
import java.util.Map;

/**
 * @author 雷春琼
 * @description 客户分配表数据库操作服务实现
 * @createDate 2017-08-15 下午7:26:47
 */
@Service
@Transactional
public class TssAllocationServiceImp extends BaseServiceImp<TssAllocation> implements ITssAllocationService {

    @Autowired
    private TssStudentServiceImp tssStudentService;
    @Autowired
    private ITssAllocationDao tssAllocationDao;

    /**
     * 新增/修改分配客户
     *
     * @param entity
     */
    @Override
    public boolean saveOrUpdate( String studentId, TssAllocation entity) {
        boolean bool = true;
        String id = entity.getId();
        Serializable newId = null;


        if (StringUtils.isNotBlank(id)) {
            TssAllocation destEntity = this.get(id);
            BeanUtils.copyProperties(entity, destEntity, "createTime");
            this.updateEntitiy(destEntity);
        } else {
            String[] studentIds = StringUtils.split(studentId, ",");
            for (String ids : studentIds) {
                TssAllocation   allocation=new TssAllocation();
                allocation.setCreateTime(new Timestamp(System.currentTimeMillis()));
                allocation.setStudentId(ids);
                allocation.setEmpAdminUserId(entity.getEmpAdminUserId());
                allocation.setAdminUserId(entity.getAdminUserId());
                newId = this.save(allocation);
            }
            //修改客户客户名单状态
            Integer tssStuId= tssStudentService.updateListStatusOrStatusByIds(ImmutableMap.of(("listStatus"), 2),entity.getEmpAdminUserId(), studentId);
            if (newId == null && tssStuId == null) {
                return !bool;
            }
        }
        return bool;
    }

    @Override
    public List<Map<String, Object>> getDetailListByMemberId(String memberId) throws Exception {
        return tssAllocationDao.getDetailListByMemberId(memberId);
    }

    @Override
    public List<TssAllocation> findByEmpAdminUserId(String empAdminUserId, String studentId) {
        return tssAllocationDao.findByEmpAdminUserId(empAdminUserId,studentId);
    }
}
